<template>
  <div class="map-section">
    <div class="section-header">
      <h3>位置监控</h3>
      <div class="map-controls">
        <button class="map-control-btn" @click="toggleMapType" :class="{ satellite: mapType === 'satellite' }">
          <span>{{ mapType === 'normal' ? '🌍' : '🛰️' }}</span>
          <span>{{ mapType === 'normal' ? '卫星' : '普通' }}</span>
        </button>
        <button class="map-control-btn" @click="centerToVehicle" :disabled="!hasLocation">
          <span>🎯</span>
          <span>居中</span>
        </button>
        <button class="map-control-btn" @click="refreshLocation">
          <span>🔄</span>
          <span>刷新</span>
        </button>
      </div>
    </div>
    
    <div class="map-container">
      <div v-if="!isMapLoaded" class="map-placeholder">
        <div class="placeholder-content">
          <div class="loading-spinner"></div>
          <p class="placeholder-text">正在加载地图...</p>
        </div>
      </div>
      
      <div id="baiduMap" class="baidu-map" v-show="isMapLoaded"></div>
      
      <div v-if="mapError" class="map-error">
        <span class="error-icon">⚠️</span>
        <p>地图加载失败</p>
        <button @click="initMap" class="retry-btn">重试</button>
      </div>
      
      <!-- 位置信息面板 -->
      <div class="location-info" v-if="currentLocation && !mapError">
        <div class="info-header">
          <span class="location-icon">📍</span>
          <span class="location-title">当前位置</span>
        </div>
        <div class="info-content">
          <div class="coordinate-item">
            <span class="label">经度:</span>
            <span class="value">{{ currentLocation.lng.toFixed(6) }}°</span>
          </div>
          <div class="coordinate-item">
            <span class="label">纬度:</span>
            <span class="value">{{ currentLocation.lat.toFixed(6) }}°</span>
          </div>
          <div class="coordinate-item" v-if="currentLocation.address">
            <span class="label">地址:</span>
            <span class="value address">{{ currentLocation.address }}</span>
          </div>
          <div class="coordinate-item" v-if="lastUpdateTime">
            <span class="label">更新:</span>
            <span class="value time">{{ lastUpdateTime }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  // 可以从外部传入经纬度
  latitude: {
    type: Number,
    default: null
  },
  longitude: {
    type: Number,
    default: null
  },
  // API配置
  apiConfig: {
    type: Object,
    default: () => ({})
  }
})

// 发射事件
const emit = defineEmits(['locationUpdate', 'mapReady'])

// 响应式数据
const isMapLoaded = ref(false)
const mapError = ref(false)
const mapType = ref('normal') // normal | satellite
const currentLocation = ref(null)
const lastUpdateTime = ref('')
const hasLocation = ref(false)

// 百度地图相关
let baiduMap = null
let vehicleMarker = null
let pathPolyline = null
let locationHistory = []

const BAIDU_API_KEY = 'c6VmXOqsui5yuAKh7SsYgrhEzvpSIsYM' // 请替换为您的API密钥

// 如果没有API密钥，使用演示模式
const DEMO_MODE = BAIDU_API_KEY === 'YOUR_BAIDU_API_KEY'

// 初始化百度地图
async function initMap() {
  try {
    mapError.value = false
    
    // 如果是演示模式，显示提示
    if (DEMO_MODE) {
      ElMessage.warning('演示模式：请申请百度地图API密钥以使用完整功能')
      // 使用静态地图演示
      initDemoMap()
      return
    }
    
    // 检查百度地图API是否已加载
    if (!window.BMap) {
      await loadBaiduMapScript()
    }

    await nextTick()
    
    // 默认中心点（可以设置为您的城市）
    const defaultCenter = new window.BMap.Point(116.404, 39.915) // 北京天安门
    
    // 创建地图实例
    baiduMap = new window.BMap.Map('baiduMap')
    
    // 设置中心点和缩放级别
    baiduMap.centerAndZoom(defaultCenter, 15)
    
    // 启用鼠标滚轮缩放
    baiduMap.enableScrollWheelZoom(true)
    
    // 添加地图控件
    baiduMap.addControl(new window.BMap.NavigationControl())
    baiduMap.addControl(new window.BMap.ScaleControl())
    baiduMap.addControl(new window.BMap.OverviewMapControl())
    
    // 如果有传入的经纬度，直接显示
    if (props.latitude && props.longitude) {
      updateVehicleLocation(props.latitude, props.longitude)
    }
    
    isMapLoaded.value = true
    emit('mapReady', baiduMap)
    
    console.log('百度地图初始化成功')
    ElMessage.success('地图加载成功')
    
  } catch (error) {
    console.error('地图初始化失败:', error)
    mapError.value = true
    ElMessage.error('地图加载失败: ' + error.message)
  }
}

// 加载百度地图脚本
function loadBaiduMapScript() {
  return new Promise((resolve, reject) => {
    if (window.BMap) {
      resolve()
      return
    }

    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `//api.map.baidu.com/api?v=3.0&ak=${BAIDU_API_KEY}&callback=initBaiduMap`
    script.onerror = () => reject(new Error('百度地图脚本加载失败'))
    
    window.initBaiduMap = () => {
      resolve()
      delete window.initBaiduMap
    }
    
    document.head.appendChild(script)
  })
}

// 更新小车位置
function updateVehicleLocation(lat, lng, address = '') {
  // 在演示模式下也要更新位置信息
  currentLocation.value = { lat, lng, address }
  lastUpdateTime.value = new Date().toLocaleTimeString()
  hasLocation.value = true
  
  // 更新位置历史
  locationHistory.push({ lat, lng, time: Date.now() })
  if (locationHistory.length > 50) {
    locationHistory.shift()
  }
  
  emit('locationUpdate', { lat, lng, address })
  
  // 如果是演示模式，不执行百度地图操作
  if (DEMO_MODE || !baiduMap) {
    return
  }
  
  try {
    const point = new window.BMap.Point(lng, lat)
    
    // 移除旧标记
    if (vehicleMarker) {
      baiduMap.removeOverlay(vehicleMarker)
    }
    
    // 创建小车图标
    const vehicleIcon = new window.BMap.Icon(
      'data:image/svg+xml;base64,' + btoa(`
        <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
          <circle cx="16" cy="16" r="12" fill="#4299e1" stroke="#ffffff" stroke-width="2"/>
          <text x="16" y="20" text-anchor="middle" fill="white" font-size="16">🚗</text>
        </svg>
      `),
      new window.BMap.Size(32, 32),
      {
        anchor: new window.BMap.Size(16, 16)
      }
    )
    
    // 创建标记
    vehicleMarker = new window.BMap.Marker(point, { icon: vehicleIcon })
    baiduMap.addOverlay(vehicleMarker)
    
    // 添加信息窗口
    const infoWindow = new window.BMap.InfoWindow(`
      <div style="font-family: Arial, sans-serif; line-height: 1.4;">
        <h4 style="margin: 0 0 8px 0; color: #333;">🚗 智能小车</h4>
        <p style="margin: 4px 0; color: #666;">
          <strong>经度:</strong> ${lng.toFixed(6)}°<br>
          <strong>纬度:</strong> ${lat.toFixed(6)}°<br>
          ${address ? `<strong>位置:</strong> ${address}<br>` : ''}
          <strong>时间:</strong> ${new Date().toLocaleString()}
        </p>
      </div>
    `)
    
    vehicleMarker.addEventListener('click', () => {
      baiduMap.openInfoWindow(infoWindow, point)
    })
    
    // 更新位置历史
    locationHistory.push({ lat, lng, time: Date.now() })
    if (locationHistory.length > 50) {
      locationHistory.shift() // 保持最近50个位置点
    }
    
    // 绘制轨迹
    updateTrajectory()
    
    // 更新当前位置信息
    currentLocation.value = { lat, lng, address }
    lastUpdateTime.value = new Date().toLocaleTimeString()
    hasLocation.value = true
    
    // 如果没有地址，尝试逆地理编码
    if (!address) {
      getAddressByLocation(lat, lng)
    }
    
    emit('locationUpdate', { lat, lng, address })
    
  } catch (error) {
    console.error('更新位置失败:', error)
    ElMessage.error('位置更新失败')
  }
}

// 逆地理编码获取地址
function getAddressByLocation(lat, lng) {
  if (!window.BMap) return
  
  const geoc = new window.BMap.Geocoder()
  const point = new window.BMap.Point(lng, lat)
  
  geoc.getLocation(point, (result) => {
    if (result) {
      const address = result.address
      if (currentLocation.value) {
        currentLocation.value.address = address
      }
    }
  })
}

// 更新轨迹线
function updateTrajectory() {
  if (!baiduMap || locationHistory.length < 2) return
  
  // 移除旧轨迹
  if (pathPolyline) {
    baiduMap.removeOverlay(pathPolyline)
  }
  
  // 创建轨迹点数组
  const points = locationHistory.map(loc => 
    new window.BMap.Point(loc.lng, loc.lat)
  )
  
  // 创建轨迹线
  pathPolyline = new window.BMap.Polyline(points, {
    strokeColor: '#4299e1',
    strokeWeight: 3,
    strokeOpacity: 0.8
  })
  
  baiduMap.addOverlay(pathPolyline)
}

// 切换地图类型
function toggleMapType() {
  if (!baiduMap) return
  
  if (mapType.value === 'normal') {
    baiduMap.setMapType(window.BMAP_SATELLITE_MAP)
    mapType.value = 'satellite'
  } else {
    baiduMap.setMapType(window.BMAP_NORMAL_MAP)
    mapType.value = 'normal'
  }
}

// 居中到小车位置
function centerToVehicle() {
  if (!baiduMap || !currentLocation.value) return
  
  const point = new window.BMap.Point(
    currentLocation.value.lng, 
    currentLocation.value.lat
  )
  baiduMap.centerAndZoom(point, 18)
}

// 刷新位置（从API获取）
async function refreshLocation() {
  try {
    if (props.apiConfig && props.apiConfig.locationEndpoint) {
      // 从API获取位置
      const response = await fetch(props.apiConfig.locationEndpoint)
      const data = await response.json()
      
      if (data.latitude && data.longitude) {
        updateVehicleLocation(data.latitude, data.longitude, data.address)
        ElMessage.success('位置更新成功')
      }
    } else {
      // 使用传入的props
      if (props.latitude && props.longitude) {
        updateVehicleLocation(props.latitude, props.longitude)
      } else {
        ElMessage.warning('没有位置数据')
      }
    }
  } catch (error) {
    console.error('刷新位置失败:', error)
    ElMessage.error('位置刷新失败')
  }
}

// 暴露方法给父组件
defineExpose({
  updateLocation: updateVehicleLocation,
  centerToVehicle,
  refreshLocation,
  clearTrajectory: () => {
    locationHistory = []
    if (pathPolyline) {
      baiduMap.removeOverlay(pathPolyline)
      pathPolyline = null
    }
  }
})

// 生命周期
onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (baiduMap) {
    baiduMap.destroy()
  }
})
</script>

<style scoped>
.map-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 1rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  padding-bottom: 0.75rem;
  border-bottom: 2px solid #e2e8f0;
}

.section-header h3 {
  font-size: 1.1rem;
  font-weight: 700;
  margin: 0;
  color: #2d3748;
}

.map-controls {
  display: flex;
  gap: 0.5rem;
}

.map-control-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 8px;
  font-size: 0.8rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #718096, #4a5568);
  color: white;
}

.map-control-btn.satellite {
  background: linear-gradient(135deg, #48bb78, #38a169);
}

.map-control-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.map-control-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.map-container {
  flex: 1;
  position: relative;
  border-radius: 10px;
  overflow: hidden;
  min-height: 400px;
}

.map-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: linear-gradient(135deg, #2d3748, #1a202c);
  color: white;
}

.placeholder-content {
  text-align: center;
}

.placeholder-text {
  font-size: 1rem;
  font-weight: 600;
  margin-top: 1rem;
}

.baidu-map {
  width: 100%;
  height: 100%;
  min-height: 400px;
}

.map-error {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(26, 32, 44, 0.9);
  color: white;
  text-align: center;
}

.loading-spinner {
  width: 30px;
  height: 30px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #4299e1;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.retry-btn {
  background: linear-gradient(135deg, #4299e1, #3182ce);
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 8px;
  cursor: pointer;
  margin-top: 1rem;
}

.location-info {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 10px;
  padding: 1rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  max-width: 250px;
  font-size: 0.9rem;
}

.info-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #e2e8f0;
}

.location-icon {
  font-size: 1.2rem;
}

.location-title {
  font-weight: 700;
  color: #2d3748;
}

.coordinate-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
  align-items: flex-start;
}

.coordinate-item:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: 600;
  color: #4a5568;
  min-width: 40px;
}

.value {
  color: #2d3748;
  font-family: 'Courier New', monospace;
  text-align: right;
  flex: 1;
  margin-left: 0.5rem;
}

.value.address {
  font-family: inherit;
  font-size: 0.8rem;
  line-height: 1.3;
}

.value.time {
  font-family: inherit;
  font-size: 0.8rem;
  color: #718096;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .location-info {
    position: relative;
    top: auto;
    left: auto;
    margin-bottom: 1rem;
    max-width: none;
  }
  
  .map-container {
    min-height: 300px;
  }
}
</style>
